import pyautogui
import time
import win32com.client
import os
import pyperclip
import pythoncom

import core.team_comm as team_comm

window_left = 0
window_wight = 0
window_top = 0
window_height = 0
game_window_left = 0
game_window_wight = 0
game_window_top = 0
game_window_height = 0


class InviteTeam:
    def __init__(self):
        pythoncom.CoInitialize()  # 初始化 COM
        self.ret_my_info = None
        self.dm = win32com.client.Dispatch("dm.dmsoft")
        print("大漠插件版本：", self.dm.Ver())
        script_dir = os.path.dirname(os.path.abspath(__file__))
        print("当前目录", script_dir)
        self.dm.SetPath(os.path.join(script_dir))

        # 关键修改1：强制设置绝对路径
        self.script_dir = os.path.dirname(os.path.abspath(__file__))
        self.dm.SetPath(self.script_dir)

        # 关键修改2：显式加载字库文件
        self.font_file = os.path.join(self.script_dir, "game_font.txt")
        if os.path.exists(self.font_file):
            # 3.1232版本必须用SetDict加载字库文件
            ret = self.dm.SetDict(0, self.font_file)
            print(f"字库加载状态: {'成功' if ret == 1 else '失败'}")
        else:
            with open(self.font_file, "w", encoding="gbk") as f:
                f.write("[game_font]\n")
            print("新建空字库文件")

    def find_game_window(self, partial_title):

        try:
            for i in range(100):
                # 获取所有包含部分标题的窗口
                windows = pyautogui.getWindowsWithTitle(partial_title)

                if windows:
                    print(f"找到 {len(windows)} 个匹配窗口:")
                    for i, win in enumerate(windows, 1):
                        print(f" 完整标题: '{win.title}'")

                    # 返回第一个匹配的窗口
                    return windows[0]
                else:
                    print(f"未找到标题包含 '{partial_title}' 的窗口，重试第'{i + 1}'次...")
                    time.sleep(1)

            print(f"未找到标题包含 '{partial_title}' 的窗口")
            return None
        except Exception as e:
            print(f"查找窗口时出错: {e}")
        return None


def invite_team(my_team_info):
    team = team_comm.TeamCommander()
    this = InviteTeam()
    game_window = this.find_game_window("Marvel Rivals")
    if game_window:
        game_window.activate()
        time.sleep(1)
        game_window_left = game_window.left - 10
        game_window_wight = game_window.width
        game_window_top = game_window.top - 10
        game_window_height = game_window.height

        # 点击最下面一个位置
        pyautogui.moveTo(x=(game_window_left + (game_window_wight * 0.2)),
                         y=(game_window_top + (game_window_height * 0.80)))
        time.sleep(1)
        pyautogui.click()

        if my_team_info:
            for one in my_team_info:

                # 搜索名字
                time.sleep(1)
                pyautogui.moveTo(x=(game_window_left + (game_window_wight * 0.90)),
                                 y=(game_window_top + (game_window_height * 0.13)))
                time.sleep(0.5)
                for i in range(5):
                    pyautogui.click()
                    time.sleep(0.2)

                time.sleep(0.5)
                pyautogui.hotkey('ctrl', 'a')
                time.sleep(0.5)
                game_name = one['game_name']
                pyperclip.copy(game_name)  # 复制到剪贴板
                pyautogui.hotkey('ctrl', 'v')  # 粘贴

                time.sleep(2)
                pyautogui.moveTo(x=(game_window_left + (game_window_wight * 0.90)),
                                 y=(game_window_top + (game_window_height * 0.17)))
                time.sleep(0.5)
                for i in range(5):
                    pyautogui.click()
                    time.sleep(0.2)
                time.sleep(2)
                pyautogui.moveTo(x=(game_window_left + (game_window_wight * 0.97)),
                                 y=(game_window_top + (game_window_height * 0.25)))
                time.sleep(1)
                for i in range(5):
                    pyautogui.click()
                    time.sleep(0.2)

                # 邀请后通知队友
                ip = one['ip']
                success = team.invite_teammates(ip)
                if not success:
                    print(f"警告: 邀请 {ip} 队友失败")
                else:
                    print(f"信息: 邀请 {ip} 队友成功")

        time.sleep(0.5)

        # 离焦点击，关闭查询侧拉框
        pyautogui.moveTo(x=(game_window_left + (game_window_wight * 0.5)),
                         y=(game_window_top + (game_window_height * 0.5)))
        time.sleep(0.5)
        for i in range(3):
            pyautogui.click()
            time.sleep(0.2)

    return True


if __name__ == '__main__':
    game_name = 'RockFish001'
    invite_team(game_name)
